<template>
  <div ref="echartsContainer" :style="{ width, height }"></div>
</template>

<script>
import { onMounted, onUnmounted, ref, watch } from 'vue';
import * as echarts from 'echarts';

export default {
  name: 'EChartsComponent',
  props: {
    option: {
      type: Object,
      required: true
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    }
  },
  setup(props) {
    const echartsContainer = ref(null);
    let chartInstance = null;

    const initChart = () => {
      chartInstance = echarts.init(echartsContainer.value);
      chartInstance.setOption(props.option);
    };

    onMounted(() => {
      initChart();
      window.addEventListener('resize', chartInstance.resize);
    });

    onUnmounted(() => {
      chartInstance && chartInstance.dispose();
      window.removeEventListener('resize', chartInstance.resize);
    });

    watch(() => props.option, (newOption) => {
      if (chartInstance) {
        chartInstance.setOption(newOption);
      }
    }, { deep: true });

    return { echartsContainer };
  }
};
</script>
